package com.plian.system.service.fr.evaluation.impl;

import com.plian.Tools.*;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.entity.fr.evaluation.EvaluationApproval;
import com.plian.system.mapper.fr.evaluation.EvaluationApprovalMapper;
import com.plian.system.mybatis.base.BaseServiceImpl;
import com.plian.system.properties.GzwProperties;
import com.plian.system.service.fr.evaluation.IAssetAppraiserInfoService;
import com.plian.system.service.fr.evaluation.IEvaluationApprovalService;
import com.plian.system.service.fr.evaluation.IEvaluationValueService;
import com.plian.system.service.sys.code.IFormCodeService;
import com.plian.system.service.wf.FormWorkflowService;
import com.plian.system.wrapper.fr.evaluation.EvaluationApprovalWrapper;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * 资产评估项目核准与备案 服务实现类
 *
 * @author jianglei
 * @since 2019-10-21
 */
@Service
@AllArgsConstructor
public class EvaluationApprovalServiceImpl extends BaseServiceImpl<EvaluationApprovalMapper, EvaluationApproval> implements IEvaluationApprovalService
//		, BaseFlowService
{


    private IAssetAppraiserInfoService assetAppraiserInfoService;

    private IEvaluationValueService evaluationValueService;

	private FormWorkflowService formWorkflowService;

	private IFormCodeService formCodeService;

	private EvaluationApprovalWrapper evaluationApprovalWrapper;

	private GzwProperties gzwProperties;

//	@Override
//    public boolean saveOrUpdate(EvaluationApproval evaluationApproval) {
//		if (evaluationApproval.getId() == null){
//			evaluationApproval.setVersion("1");
//			evaluationApproval.setCode(formCodeService.getCode(FormTypeConstant.FR_EVALUATIONAPPROVAL_FORM));
//			evaluationApproval.setFormType(String.valueOf(FormTypeConstant.FR_EVALUATIONAPPROVAL_FORM));
//		}
//        return super.saveOrUpdate(evaluationApproval);
//    }
//
//    @Override
//    public boolean deleteLogic(List<Long> ids) {
//		for (Long id : ids) {
//			EvaluationApproval evaluationApproval = getById(id);
//			if (evaluationApproval == null) {
//				return false;
//			} else if (evaluationApproval.getStatus() != null &&
//					(evaluationApproval.getStatus() != FormStatusConstant.STASH && evaluationApproval.getStatus() != FormStatusConstant.UNREVIEWED)) {
//				return false;
//			}
//			formWorkflowService.deleteProcessInstance(String.valueOf(id));
//		}
//		boolean result = super.deleteLogic(ids);
//		evaluationValueService.deleteLogicByEvaluationApprovalId(ids);
//		assetAppraiserInfoService.deleteLogicByEvaluationApprovalId(ids);
//		return result;
//    }
//
//    @Override
//    public HashMap<String,Object> commit(String id) {
//		handleStatus(Long.valueOf(id), FormStatusConstant.FLOW);
//
//		//将需要提交的流程变量返回，用于工作流侧
//		return new HashMap<String,Object>();
//    }
//
//    @Override
//    public Boolean finish(String id) {
//		/**
//		 * 设置审批人和审批时间
//		 */
//		EvaluationApproval evaluationApproval = getById(id);
//		Date now = DateUtil.now();
//		evaluationApproval.setApprovedTime(now);
//
//		if (evaluationApproval.getApprovalOrFiling() != null){
//			if (evaluationApproval.getApprovalOrFiling() == 1){
//				if (StringUtil.isBlank(evaluationApproval.getApprovalCode())){
//					String code = formCodeService.getFilingCode(FormTypeConstant.FR_EVALUATIONAPPROVAL_FORM);
//					evaluationApproval.setApprovalCode(gzwProperties.getCodeStartName() + "评核字〔" + code.substring(0,4) + "〕" + code.substring(code.length()-3) + "号");
//				}
//			}else {
//				if (StringUtil.isBlank(evaluationApproval.getFilingCode())){
//					String code = formCodeService.getFilingCode(FormTypeConstant.FR_EVALUATIONAPPROVAL_FORM);
//					evaluationApproval.setFilingCode(gzwProperties.getCodeStartName() + "评备字〔" + code.substring(0,4) + "〕" + code.substring(code.length()-3) + "号");
//				}
//			}
//		}
//
//		updateById(evaluationApproval);
//
//		return handleStatus(Long.valueOf(id), FormStatusConstant.FINISH);
//    }
//
//    @Override
//    public Boolean reject(String id, int formState, String comment) {
//		return handleStatus(Long.valueOf(id), formState);
//    }
//
//
//	@Override
//	public Boolean checkIsExisted(Long id, String approvalCode, String filingCode) {
//
//		return true;
//	}
//
//	@Override
//	public Boolean checkCode(Long id, String code) {
//		if (Optional.ofNullable(code).isPresent()) {
//			EvaluationApproval evaluationApproval = new EvaluationApproval();
//			evaluationApproval.setCode(code);
//			if (Optional.ofNullable(getOne(Condition.getQueryWrapper(evaluationApproval))).isPresent()) {
//				if (id==null || !id.equals(getOne(Condition.getQueryWrapper(evaluationApproval)).getId())){
//					return false;
//				}
//			}
//		}
//		return true;
//	}
//
//	@Override
//	@Transactional(rollbackFor=RuntimeException.class)
//	public Boolean submit(EvaluationApproval evaluationApproval) {
//		if (!Optional.ofNullable(evaluationApproval.getStatus()).isPresent()){
//			evaluationApproval.setStatus(FormStatusConstant.UNREVIEWED);
//		}
//
//		boolean result = saveOrUpdate(evaluationApproval);
//		List<AssetAppraiserInfo> assetAppraiserInfos = evaluationApproval.getAssetAppraiserInfos();
//		if (CollectionUtil.isNotEmpty(assetAppraiserInfos)){
//			/**
//			 * 评估师信息
//			 */
//			List<Long> delIds = assetAppraiserInfos.stream().filter(assetAppraiserInfo ->
//				Optional.ofNullable(assetAppraiserInfo.getIsDeleted()).isPresent() && assetAppraiserInfo.getIsDeleted() == 1)
//				.map(AssetAppraiserInfo::getId).collect(Collectors.toList());
//			if (CollectionUtil.isNotEmpty(delIds)){
//				assetAppraiserInfoService.deleteLogic(delIds);
//			}
//
//			assetAppraiserInfos.removeIf(assetAppraiserInfo -> (Optional.ofNullable(assetAppraiserInfo.getIsDeleted()).isPresent() && assetAppraiserInfo.getIsDeleted() == 1));
//
//
//			if (CollectionUtil.isNotEmpty(assetAppraiserInfos)) {
//				/**
//				 * 给新增数据赋值
//				 */
//				assetAppraiserInfos.stream().filter(assetAppraiserInfo -> assetAppraiserInfo.getId() == null)
//					.forEach(assetAppraiserInfo -> {
//						assetAppraiserInfo.setEvaluationApprovalId(evaluationApproval.getId());
//						assetAppraiserInfo.setStatus(FormStatusConstant.UNREVIEWED);
//						assetAppraiserInfo.setIsDeleted(0);
//					});
//				assetAppraiserInfoService.saveOrUpdateBatch(assetAppraiserInfos);
//			}
//		}
//
//		List<EvaluationValue> evaluationValues = evaluationApproval.getEvaluationValues();
//		if (CollectionUtil.isNotEmpty(evaluationValues)){
//			/**
//			 * 评估价值
//			 */
//			List<Long> delIds = evaluationValues.stream().filter(evaluationValue ->
//				Optional.ofNullable(evaluationValue.getIsDeleted()).isPresent() && evaluationValue.getIsDeleted() == 1)
//				.map(EvaluationValue::getId).collect(Collectors.toList());
//			if (CollectionUtil.isNotEmpty(delIds)){
//				evaluationValueService.deleteLogic(delIds);
//			}
//
//			evaluationValues.removeIf(evaluationValue -> (Optional.ofNullable(evaluationValue.getIsDeleted()).isPresent() && evaluationValue.getIsDeleted() == 1));
//
//
//			if (CollectionUtil.isNotEmpty(evaluationValues)) {
//				/**
//				 * 给新增数据赋值
//				 */
//				evaluationValues.stream().filter(evaluationValue -> evaluationValue.getId() == null)
//					.forEach(evaluationValue -> {
//						evaluationValue.setEvaluationApprovalId(evaluationApproval.getId());
//						evaluationValue.setStatus(FormStatusConstant.UNREVIEWED);
//						evaluationValue.setIsDeleted(0);
//					});
//				evaluationValueService.saveOrUpdateBatch(evaluationValues);
//			}
//		}
//
//		HashMap<String, Object> processVariable = new HashMap<>();
//		formWorkflowService.startProcessAndSimulate(String.valueOf(evaluationApproval.getId()),evaluationApproval.getFormType(),processVariable);
//
//		return result;
//	}
//	@Override
//	public File exportExcel(JSONObject jsonObject) {
//		List<SearchEntity> entityList = Optional.ofNullable(jsonObject.getJSONArray("query"))
//			.map(x -> x.toJavaList(SearchEntity.class)).orElse(new ArrayList<>());
//		QueryWrapper<EvaluationApproval> qw= SearchParamEntiy.getQueryWrapper(
//			Condition.getQueryWrapper(new EvaluationApproval()), entityList
//		);
//
//		List<EvaluationApproval> floors = list(qw);
//		return null;
////		return ExcelUtils.exportExcelByList(jsonObject, EvaluationApprovalWrapper.build().listVO(floors));
//	}
//	@Override
//	public Boolean change(EvaluationApproval evaluationApproval) {
//		EvaluationApproval old = getById(evaluationApproval.getId());
//		EvaluationValue evaluationValue = new EvaluationValue();
//		evaluationValue.setEvaluationApprovalId(old.getId());
//		old.setEvaluationValues(evaluationValueService.list(Condition.getQueryWrapper(evaluationValue)));
//		AssetAppraiserInfo assetAppraiserInfo = new AssetAppraiserInfo();
//		assetAppraiserInfo.setEvaluationApprovalId(old.getId());
//		old.setAssetAppraiserInfos(assetAppraiserInfoService.list(Condition.getQueryWrapper(assetAppraiserInfo)));
//		//		snapshotClient.push("evaluationApproval", old.getId(), jsonObject);
//		//evaluationApproval.setStatus(BillStatus.INIT.billStatus());
//		evaluationApproval.setVersion(StringUtil.isBlank(evaluationApproval.getVersion()) ?
//			"1" : String.valueOf(Integer.valueOf(evaluationApproval.getVersion())+1));
//		return submit(evaluationApproval);
//	}
//
//	/**
//     * 统一处理状态机事件方法
//     * @param id 主键
//     * @param updateStatus 更新状态
//     * @return boolean
//     */
//    private Boolean handleStatus(Long id, int updateStatus) {
//        try {
//            EvaluationApproval evaluationApproval = getById(id);
////            if (evaluationApproval.getStatus() != judgeStatus) {
////                 return false;
////             }
//			evaluationApproval.setStatus(updateStatus);
//            updateById(evaluationApproval);
//            return true;
//        } catch (Exception e) {
//            log.error(ExceptionUtils.getFullStackTrace(e));
//            return false;
//        }
//    }
//	@Override
//	public File buildpdf(Long id) {
//		EvaluationApprovalVO bean = evaluationApprovalWrapper.entityToVO(getById(id));
//
//		File file = null ;
//		try {
//			InputStream inputStream = this.getClass().getResourceAsStream("/pdf/evaluationapproval.pdf");
//			//通过将文件转换为临时文件进行操作
//			File model = File.createTempFile("model", ".png");
//			try {
//				FileUtils.copyInputStreamToFile(inputStream, model);
//			} finally {
//				//关闭IO
//				IOUtils.closeQuietly(inputStream);
//			}
//			/*InputStream inputStream2 = resourceLoader.getResource("4DB6230D1BF52D9A012171F8493CF278.png").getInputStream();
//			//通过将文件转换为临时文件进行操作
//			File image = File.createTempFile("logoImage1", ".png");
//			try {
//				FileUtils.copyInputStreamToFile(inputStream2, image);
//			} finally {
//				//关闭IO
//				IOUtils.closeQuietly(inputStream2);
//			}
//			images.put("logoImage1",!image.exists()?"":image.getAbsolutePath());*/
//			if (bean!=null&&model.exists()) {
//				EvaluationValue evaluationValue = new EvaluationValue();
//				evaluationValue.setEvaluationApprovalId(bean.getId());
//				bean.setEvaluationValues(evaluationValueService.list(Condition.getQueryWrapper(evaluationValue)));
//
//				AssetAppraiserInfo assetAppraiserInfo = new AssetAppraiserInfo();
//				assetAppraiserInfo.setEvaluationApprovalId(bean.getId());
//				bean.setAssetAppraiserInfos(assetAppraiserInfoService.list(Condition.getQueryWrapper(assetAppraiserInfo)));
//				Map< String,String > images=new HashMap<>(16);
//				Map< String,Object > data = OutPdf.beanToMap(bean);
//				List<AssetAppraiserInfo> assetAppraiserInfos = bean.getAssetAppraiserInfos();
//				if (assetAppraiserInfos!=null) {
//					for (int x = 0; x < assetAppraiserInfos.size(); x++) {
//						data.put("p.name." + x, assetAppraiserInfos.get(x).getRegisteredAssetAppraiser());
//						data.put("p.appraiserCode." + x, assetAppraiserInfos.get(x).getAppraiserCode());
//						data.put("p.phone." + x, assetAppraiserInfos.get(x).getContactNumber());
//					}
//				}
//				List<EvaluationValue> evaluationValues = bean.getEvaluationValues();
//				if (evaluationValues!=null) {
//					BigDecimal a1 = BigDecimal.ZERO;
//					BigDecimal a2 = BigDecimal.ZERO;
//					BigDecimal a3 = BigDecimal.ZERO;
//					BigDecimal a4 = BigDecimal.ZERO;
//					BigDecimal a5 = BigDecimal.ZERO;
//					BigDecimal a6 = BigDecimal.ZERO;
//					for (EvaluationValue x : evaluationValues) {
//						if (x.getBookValueAssets() != null) {
//							a1 = a1.add(x.getBookValueAssets());
//						}
//						if (x.getBookValueLiability() != null) {
//							a2 = a2.add(x.getBookValueLiability());
//						}
//						if (x.getBookValueNet() != null) {
//							a3 = a3.add(x.getBookValueNet());
//						}
//						if (x.getEvaluationAssets() != null) {
//							a4 = a4.add(x.getEvaluationAssets());
//						}
//						if (x.getEvaluationLiability() != null) {
//							a5 = a5.add(x.getEvaluationLiability());
//						}
//						if (x.getEvaluationNetAssets() != null) {
//							a6 = a6.add(x.getEvaluationNetAssets());
//						}
//					}
//					data.put("e.bookValueAssets", a1);
//					data.put("e.bookValueLiability", a2);
//					data.put("e.bookValueNet", a3);
//					data.put("e.evaluationAssets", a4);
//					data.put("e.evaluationLiability", a5);
//					data.put("e.evaluationNetAssets", a6);
//				}
//				String fileName = model.getPath();
//				PdfReader reader = new PdfReader(fileName);
//				ByteArrayOutputStream bos = new ByteArrayOutputStream();
//				/* 将要生成的目标PDF文件名称 */
//				PdfStamper ps = new PdfStamper(reader, bos);
//				/* 使用中文字体 */
//				BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
//				ArrayList< BaseFont > fontList = new ArrayList <> ();
//				fontList.add(bf);
//
//				/* 取出报表模板中的所有字段 */
//				AcroFields fields = ps.getAcroFields();
//				fields.setSubstitutionFonts(fontList);
//				for (String key: data.keySet()) {
//					if (data.get(key)!=null) {
//						String value = data.get(key).toString();
//						if (data.get(key) instanceof Date) {
//							value = processDate((Date) data.get(key));
//						}
//						fields.setField(key, value);
//					}
//				}
//				if (data.get("activityTypeName") != null && StringUtil.isNotBlank(data.get("activityTypeName").toString())){
//					switch (data.get("activityTypeName").toString()){
//						case "企业改制":
//							fields.setField("toggle_1", "On", true);
//							break;
//						case "企业上市":
//							fields.setField("toggle_2", "On", true);
//							break;
//						case "企业合并":
//							fields.setField("toggle_3", "On", true);
//							break;
//						case "企业分立":
//							fields.setField("toggle_4", "On", true);
//							break;
//						case "企业清算":
//							fields.setField("toggle_5", "On", true);
//							break;
//						case "非上市公司国有股东股权比例变动":
//							fields.setField("toggle_6", "On", true);
//							break;
//						case "资产转让":
//							fields.setField("toggle_7", "On", true);
//							break;
//						case "资产置换":
//							fields.setField("toggle_8", "On", true);
//							break;
//						case "资产抵债":
//							fields.setField("toggle_9", "On", true);
//							break;
//						case "资产对外投资":
//							fields.setField("toggle_10", "On", true);
//							break;
//						case "定向收购非国有单位资产":
//							fields.setField("toggle_11", "On", true);
//							break;
//						case "接受非国有单位出资":
//							fields.setField("toggle_12", "On", true);
//							break;
//						case "其他":
//							fields.setField("toggle_13", "On", true);
//							break;
//						default:
//							break;
//					}
//				}
//
//				/*if (images!=null) {
//					for (String key : images.keySet()) {
//						if (!StringUtil.isEmpty(images.get(key))) {
//							//待加入图片的文字域,设置为隐藏;不然会遮挡掉图片的
//							OutPdf.insertImage(fields, ps, key, images.get(key));
//						}
//					}
//				}*/
//				/* 必须要调用这个，否则文档不会生成的 */
//				ps.setFormFlattening(true);
//				ps.close();
//				File dir = new File(model.getParent());
//				String classFullName = bean.getClass().getName();
//				file = File.createTempFile(classFullName.substring(classFullName.lastIndexOf(".")), ".pdf", dir);
//				OutputStream fos = new FileOutputStream(file);
//				fos.write(bos.toByteArray());
//				fos.flush();
//				fos.close();
//				bos.close();
//			}
//
//		} catch(Exception e) {
//			log.error(ExceptionUtils.getFullStackTrace(e));
//		}
//		return file;
//	}
//
//	@Override
//	public List<PageData> findByIds(List<String> formIds) {
//		LambdaQueryWrapper<EvaluationApproval> queryWrapper = new LambdaQueryWrapper<>();
//		queryWrapper.in(EvaluationApproval::getId, Func.toLongList(StringUtils.join(formIds, StringPool.COMMA)));
//		List<EvaluationApproval> evaluationApprovals = list(queryWrapper);
//		List<EvaluationApprovalVO> evaluationApprovalVOS = evaluationApprovalWrapper.entityToVO(evaluationApprovals);
//		List<PageData> pageDataList = new ArrayList<>();
//		try{
//			if (CollectionUtil.isNotEmpty(evaluationApprovalVOS)){
//				for (EvaluationApprovalVO vo : evaluationApprovalVOS){
//					PageData pd = new PageData();
//					pd.put("id", vo.getId());
//					pd.put("UNITNAME", vo.getPossessionCompanyName());
//					pd.put("APPLICANTNAME", vo.getCreateUserName());
//					pd.put("applicantId", vo.getCreateUser());
//					pd.put("applyOrganizationId", vo.getPossessionCompanyId());
//					pd.put("formType", FormTypeConstant.FR_EVALUATIONAPPROVAL_FORM);
//					pd.put("orgName", vo.getPossessionCompanyName());
//					pageDataList.add(pd);
//				}
//			}
//
//			return pageDataList;
//		} catch (Exception e) {
//			log.error(ExceptionUtils.getFullStackTrace(e));
//		}
//		return pageDataList;
//	}
//
//	@Override
//	public List<Integer> getFormType() {
//		return Arrays.asList(FormTypeConstant.FR_EVALUATIONAPPROVAL_FORM);
//	}
//
//	private static String processDate(Date date){
//		SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日");
//		return date==null?"":format.format(date);
//	} TODO DEL

	@Override
	public void privilegeToModifyCode(String formId, PageData params) {

		EvaluationApproval evaluationApproval = new EvaluationApproval();
		evaluationApproval.setId(Long.valueOf(formId));

		String approvalCode = (String)params.get("approvalCode");
		if (StringUtil.isNotBlank(approvalCode)) {
			evaluationApproval.setApprovalCode(approvalCode);
		}

		String filingCode = (String)params.get("filingCode");
		if (StringUtil.isNotBlank(filingCode)){
			evaluationApproval.setFilingCode(filingCode);
		}

		updateById(evaluationApproval);
	}

//	@Override
//	public void goBackToStash(String formId) {
//		handleStatus(Long.valueOf(formId), UNREVIEWED);
//	}
}
